package com.my.oschina.ui;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.my.oschina.R;
import com.my.oschina.app.AppContext;
import com.my.oschina.app.AppException;
import com.my.oschina.bean.FriendList;
import com.my.oschina.bean.MyInformation;
import com.my.oschina.bean.Result;
import com.my.oschina.common.FileUtils;
import com.my.oschina.common.ImageUtils;
import com.my.oschina.common.StringUtils;
import com.my.oschina.common.UIHelper;

/**
 * 侧边导航-用户资料
 * 
 * @version 1.0
 * @created 2013-07-01
 */
public class UserInfoActivity extends OscBaseActivity {

	private ImageView face;
	private ImageView gender;
	private TextView name;
	private TextView jointime;
	private TextView from;
	private TextView devplatform;
	private TextView expertise;
	private TextView followers;
	private TextView fans;
	private TextView favorites;
	private LinearLayout favorites_ll;
	private LinearLayout followers_ll;
	private LinearLayout fans_ll;
	// private LoadingDialog loading;
	private MyInformation user;
	private Handler mHandler;

	private final static int CROP = 200;
	private final static String FILE_SAVEPATH = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/OSChina/Portrait/";
	private Uri origUri;
	private Uri cropUri;
	private File protraitFile;
	private Bitmap protraitBitmap;
	private String protraitPath;

	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_info);

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setLogo(R.drawable.slm_action_user);
		setTitle(R.string.main_menu_myinfo);
		// 初始化视图控件
		this.initView();
		// 初始化视图数据
		this.initData();
	}

	private void initView() {

		face = (ImageView) findViewById(R.id.user_info_userface);
		gender = (ImageView) findViewById(R.id.user_info_gender);
		name = (TextView) findViewById(R.id.user_info_username);
		jointime = (TextView) findViewById(R.id.user_info_jointime);
		from = (TextView) findViewById(R.id.user_info_from);
		devplatform = (TextView) findViewById(R.id.user_info_devplatform);
		expertise = (TextView) findViewById(R.id.user_info_expertise);
		followers = (TextView) findViewById(R.id.user_info_followers);
		fans = (TextView) findViewById(R.id.user_info_fans);
		favorites = (TextView) findViewById(R.id.user_info_favorites);
		favorites_ll = (LinearLayout) findViewById(R.id.user_info_favorites_ll);
		followers_ll = (LinearLayout) findViewById(R.id.user_info_followers_ll);
		fans_ll = (LinearLayout) findViewById(R.id.user_info_fans_ll);
	}

	private void initData() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// if (loading != null)
				// loading.dismiss();
				setSupportProgressBarIndeterminateVisibility(false);
				// 刷新成功
				if (msg.what == 1 && msg.obj != null) {
					user = (MyInformation) msg.obj;
					// 加载用户头像
					UIHelper.showUserFace(face, user.getFace());
					// 用户性别
					if (user.getGender() == 1) {
						gender.setImageResource(R.drawable.widget_gender_man);
					} else {
						gender.setImageResource(R.drawable.widget_gender_woman);
					}

					// 其他资料
					name.setText(user.getName());
					jointime.setText(StringUtils.friendly_time(user
							.getJointime()));
					from.setText(user.getFrom());
					devplatform.setText(user.getDevplatform());
					expertise.setText(user.getExpertise());
					followers.setText(user.getFollowerscount() + "");
					fans.setText(user.getFanscount() + "");
					favorites.setText(user.getFavoritecount() + "");

					favorites_ll.setOnClickListener(favoritesClickListener);
					fans_ll.setOnClickListener(fansClickListener);
					followers_ll.setOnClickListener(followersClickListener);

				} else if (msg.obj != null) {
					((AppException) msg.obj).makeToast(UserInfoActivity.this);
				}
			}
		};
		this.loadUserInfoThread(false);
	}

	private void loadUserInfoThread(final boolean isRefresh) {
		// loading = new LoadingDialog(this);
		// loading.show();
		setSupportProgressBarIndeterminateVisibility(true);

		new Thread() {
			@Override
			public void run() {
				Message msg = new Message();
				try {
					MyInformation user = ((AppContext) getApplication())
							.getMyInformation(isRefresh);
					msg.what = 1;
					msg.obj = user;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				mHandler.sendMessage(msg);
			}
		}.start();
	}

	/**
	 * 收藏
	 */
	private View.OnClickListener favoritesClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			UIHelper.showUserFavorite(v.getContext());
		}
	};

	/**
	 * 粉丝
	 */
	private View.OnClickListener fansClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			int followers = user != null ? user.getFollowerscount() : 0;
			int fans = user != null ? user.getFanscount() : 0;
			UIHelper.showUserFriend(v.getContext(), FriendList.TYPE_FANS,
					followers, fans);
		}
	};

	/**
	 * 关注
	 */
	private View.OnClickListener followersClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			int followers = user != null ? user.getFollowerscount() : 0;
			int fans = user != null ? user.getFanscount() : 0;
			UIHelper.showUserFriend(v.getContext(), FriendList.TYPE_FOLLOWER,
					followers, fans);
		}
	};

	/**
	 * 操作选择
	 * 
	 * @param items
	 */
	public void imageChooseItem(CharSequence[] items) {
		AlertDialog imageDialog = new AlertDialog.Builder(this)
				.setTitle("上传头像").setIcon(android.R.drawable.btn_star)
				.setItems(items, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int item) {
						// 判断是否挂载了SD卡
						String storageState = Environment
								.getExternalStorageState();
						if (storageState.equals(Environment.MEDIA_MOUNTED)) {
							File savedir = new File(FILE_SAVEPATH);
							if (!savedir.exists()) {
								savedir.mkdirs();
							}
						} else {
							UIHelper.ToastMessage(UserInfoActivity.this,
									"无法保存上传的头像，请检查SD卡是否挂载");
							return;
						}

						// 输出裁剪的临时文件
						String timeStamp = new SimpleDateFormat(
								"yyyyMMddHHmmss").format(new Date());
						// 照片命名
						String origFileName = "osc_" + timeStamp + ".jpg";
						String cropFileName = "osc_crop_" + timeStamp + ".jpg";

						// 裁剪头像的绝对路径
						protraitPath = FILE_SAVEPATH + cropFileName;
						protraitFile = new File(protraitPath);

						origUri = Uri.fromFile(new File(FILE_SAVEPATH,
								origFileName));
						cropUri = Uri.fromFile(protraitFile);

						// 相册选图
						if (item == 0) {
							startActionPickCrop(cropUri);
						}
						// 手机拍照
						else if (item == 1) {
							startActionCamera(origUri);
						}
					}
				}).create();

		imageDialog.show();
	}

	/**
	 * 选择图片裁剪
	 * 
	 * @param output
	 */
	private void startActionPickCrop(Uri output) {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		intent.putExtra("output", output);
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);// 裁剪框比例
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", CROP);// 输出图片大小
		intent.putExtra("outputY", CROP);
		startActivityForResult(Intent.createChooser(intent, "选择图片"),
				ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
	}

	/**
	 * 相机拍照
	 * 
	 * @param output
	 */
	private void startActionCamera(Uri output) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
		startActivityForResult(intent,
				ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
	}

	/**
	 * 拍照后裁剪
	 * 
	 * @param data
	 *            原始图片
	 * @param output
	 *            裁剪后图片
	 */
	private void startActionCrop(Uri data, Uri output) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(data, "image/*");
		intent.putExtra("output", output);
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);// 裁剪框比例
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", CROP);// 输出图片大小
		intent.putExtra("outputY", CROP);
		startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
	}

	/**
	 * 上传新照片
	 */
	private void uploadNewPhoto() {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// if (loading != null)
				// loading.dismiss();
				getSupportActionBar().setSubtitle(null);
				setSupportProgressBarIndeterminateVisibility(false);
				if (msg.what == 1 && msg.obj != null) {
					Result res = (Result) msg.obj;
					// 提示信息
					UIHelper.ToastMessage(UserInfoActivity.this,
							res.getErrorMessage());
					if (res.OK()) {
						// 显示新头像
						face.setImageBitmap(protraitBitmap);
					}
				} else if (msg.what == -1 && msg.obj != null) {
					((AppException) msg.obj).makeToast(UserInfoActivity.this);
				}
			}
		};

		// if (loading != null) {
		// loading.setLoadText("正在上传头像···");
		// loading.show();
		// }

		getSupportActionBar().setSubtitle("正在上传头像");
		setSupportProgressBarIndeterminateVisibility(true);

		new Thread() {
			@Override
			public void run() {
				// 获取头像缩略图
				if (!StringUtils.isEmpty(protraitPath) && protraitFile.exists()) {
					protraitBitmap = ImageUtils.loadImgThumbnail(protraitPath,
							200, 200);
				}

				if (protraitBitmap != null) {
					Message msg = new Message();
					try {
						Result res = ((AppContext) getApplication())
								.updatePortrait(protraitFile);
						if (res != null && res.OK()) {
							// 保存新头像到缓存
							String filename = FileUtils.getFileName(user
									.getFace());
							ImageUtils.saveImage(UserInfoActivity.this,
									filename, protraitBitmap);
						}
						msg.what = 1;
						msg.obj = res;
					} catch (AppException e) {
						e.printStackTrace();
						msg.what = -1;
						msg.obj = e;
					} catch (IOException e) {
						e.printStackTrace();
					}
					handler.sendMessage(msg);
				}
			};
		}.start();
	}

	@Override
	protected void onActivityResult(final int requestCode,
			final int resultCode, final Intent data) {
		if (resultCode != RESULT_OK)
			return;

		switch (requestCode) {
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
			startActionCrop(origUri, cropUri);// 拍照后裁剪
			break;
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:
			uploadNewPhoto();// 上传新照片
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_userinfo, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case R.id.menu_userinfo_edit_btn:
			CharSequence[] items = { getString(R.string.img_from_album),
					getString(R.string.img_from_camera) };
			imageChooseItem(items);
			break;
		case R.id.menu_userinfo_refresh_btn:
			loadUserInfoThread(true);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}
